//
//  LXLTabBarItem.swift
//  Weibo-YQY-test
//
//  Created by Lang on 10/20/15.
//  Copyright © 2015 Lang. All rights reserved.
//

import UIKit

class LXLTabBarItem: UITabBarItem {
    
    var index: Int = 0
    
    override var badgeValue: String?{
        didSet{
            //badgeValue 设置完成之后就会调用这个方法
            
            setBadgeViewBackImage()
        }
    }
    // 设置 bageViewBackImage 的背景
    private func setBadgeViewBackImage(){
        //拿到显示 badgeValue的控件
        
        let target = self.valueForKeyPath("_target") as! UITabBarController
        
        
        //拿到 tabbar
        for tabBarChild in target.tabBar.subviews{
            
            //拿到 UITabBarButton
            if tabBarChild .isKindOfClass(NSClassFromString("UITabBarButton")!){
                for tabBarButtonChild in tabBarChild.subviews{
                    //拿到 UIBadgeView
                    if tabBarButtonChild.isKindOfClass(NSClassFromString("_UIBadgeView")!){
                        
                        for badgeViewChild in tabBarButtonChild.subviews {
                            if badgeViewChild.isKindOfClass(NSClassFromString("_UIBadgeBackground")!) {
                                
                                //
                                var count: UInt32 = 0
                                //获取到类身上的实例变量,也叫成员变量
                                let ivars = class_copyIvarList(NSClassFromString("_UIBadgeBackground"), &count)
                                
                                for i in 0..<count {
                                    //取某一个实例变量
                                    let ivar = ivars[Int(i)]
                                    
                                    let ivarName = NSString(CString: ivar_getName(ivar), encoding: NSUTF8StringEncoding)
                                    let ivarType = NSString(CString: ivar_getTypeEncoding(ivar), encoding: NSUTF8StringEncoding)
                                    
                                    printLog("name:\(ivarName), type:\(ivarType)")
                                    
                                    if ivarName!.isEqualToString("_image"){
                                        badgeViewChild.setValue(UIImage(named: "main_badge"), forKeyPath: (ivarName! as String))
                                    }
                                }
                                
                                
                            }
                        }
                        
                        
                    }
                    
                }
                
            }
            
        }
        

        
    }
    
    
}
